import { BUNDLE_TYPE_ENUM, EVENT_NAME_ENUM, RELEASE_TYPE_ENUM } from "../base/EnumIndex";
import { AudioManager1 } from "../manager/AudioManager1";
import { EventManager } from "../manager/EventManager";
import { LevelManager } from "../manager/LevelManager";
import { UIManager } from "../manager/UIManager";
import { AdManager } from "../ads/AdManager";
import { ResManager1 } from "../manager/ResManager1";
import { GameManager } from "../manager/GameManager";
import ListView from "../component/ListView/ListView";
import { Tools } from "../common/Tools";
import { LvInfo } from "../model/OtherModel";
import { IViewData } from "../../Interface/IMessage";
import { EBundleType, EViewType } from "../../Common/Enum";
import AppService from "../../Service/AppService";
import BaseView from "../../Base/BaseView";
import Message from "../../Common/Message";
import EventID from "../../Common/EventID";
import TownUI from "../../game/town/TownUI";
import HomeUI from "../../game/home/HomeUI";
import GameUI from "../../game/GameUI";
import StorageUtil from "../../Util/StorageUtil";
import { TalkModule } from "../../Common/TalkModule";

const { ccclass, property } = cc._decorator;
const LEVEL_NUM_IN_PAGE = 6;

const VIEW_DATA: IViewData = {
    name: 'LevelUI',
    type: EViewType.Panel,
    bundle: EBundleType.NaoDong,
    zIndex: 100,
};
@ccclass
export default class LevelUI extends BaseView {
    @property({ type: cc.Node, displayName: "背景节点" })
    bg: cc.Node = null;

    @property({ type: cc.Button, displayName: "关闭按钮" })
    closeBtn: cc.Button = null;
    @property({ type: cc.Label })
    pageIdxLbl: cc.Label = null;    //当前页数
    @property({ type: cc.Label })
    totalPageLbl: cc.Label = null;    //总页数

    @property(ListView)
    listView: ListView = null;

    @property(cc.Node)
    unlockAllBtn: cc.Node = null;
    @property(cc.Node)
    giftBtn: cc.Node = null;
    @property(cc.Node)
    addBtn: cc.Node = null;

    @property({ type: cc.Button, displayName: "常玩按钮" })
    changwanBtn: cc.Button = null;

    @property({ type: cc.EditBox, displayName: "搜索关卡" })
    searchBox: cc.EditBox = null;
    @property({ type: cc.Button, displayName: "搜索" })
    btnSearch: cc.Button = null;

    @property({ type: cc.Button, displayName: "最新关卡" })
    newLv: cc.Button = null;
    @property({ type: cc.Button, displayName: "更多关卡" })
    moreLv: cc.Button = null;

    @property(cc.Node)
    liveLvCon: cc.Node = null;
    @property({ type: cc.Node })
    liveLvName: cc.Node = null;
    @property({ type: cc.Node })
    btnSuggest: cc.Node = null;
    @property({ type: cc.Button, displayName: "入口奖励按钮" })
    entryBtn: cc.Button = null;

    tempLvName: string = "";
    isTouchedPage: boolean = false;
    isSelectLvType: boolean = false;
    onLoad() {

        // AdManager.isShowSearch((active: boolean) => {
        //     this.btnSearch.node.active = this.searchBox.node.active = active;
        //     // this.btnSearch.node.active = this.searchBox.node.active = true;
        // });

        // UIManager.ins.close("LoadGameUI");

        let root = this.node.getChildByName("root");
        root.opacity = 0;

        // AudioManager1.playBG("startBgm", 1);
        EventManager.ins.on(EVENT_NAME_ENUM.UNLOCK_LEVEL, this.unlockLevel, this);
        EventManager.ins.on(EVENT_NAME_ENUM.UNLOCK_ALL_LEVEL, this.unlockAllLevel, this);

        EventManager.ins.on(EVENT_NAME_ENUM.HIDE_GIFT_BTN, this.hideGiftBtn, this);
        EventManager.ins.on(EVENT_NAME_ENUM.HIDE_ADD_SHORTCUT_BTN, this.hideAddBtn, this);
        EventManager.ins.on(EVENT_NAME_ENUM.UPDATE_LEVEL_PAGE_LABEL, this.updatePageLab, this);

        EventManager.ins.on(EVENT_NAME_ENUM.UPDATE_LIVE_LEVEL_LIST, this.updateLiveLvList, this);
    }
    onDestroy() {
        EventManager.ins.off(EVENT_NAME_ENUM.UNLOCK_LEVEL, this.unlockLevel, this);
        EventManager.ins.off(EVENT_NAME_ENUM.UNLOCK_ALL_LEVEL, this.unlockAllLevel, this);

        EventManager.ins.off(EVENT_NAME_ENUM.HIDE_GIFT_BTN, this.hideGiftBtn, this);
        EventManager.ins.off(EVENT_NAME_ENUM.HIDE_ADD_SHORTCUT_BTN, this.hideAddBtn, this);
        EventManager.ins.off(EVENT_NAME_ENUM.UPDATE_LEVEL_PAGE_LABEL, this.updatePageLab, this);
        EventManager.ins.off(EVENT_NAME_ENUM.UPDATE_LIVE_LEVEL_LIST, this.updateLiveLvList, this);

        this.unscheduleAllCallbacks();
    }
    async start() {
        ResManager1.ins.releaseLevelBundle();
        AdManager.stopVideoScreen();
        AdManager.reportHomeView();
        let infos = LevelManager.ins.getLvInfoArr();

        if (!infos) {
            await LevelManager.ins.init(() => {
                this.showRecommendUI();
                this.initScrollView();
            });
        } else {
            this.showRecommendUI();
            this.initScrollView();
        }

        this.initBtnClick();
        this.initUnlockBtn();
        this.initGiftBtn();
        this.initAddBtn();
        this.startAnim();
        this.updateAddLiveState();
        this.initLvBtn();
        if (LevelManager.ins.isSelectNewList) {
            this.selectNewList(LevelManager.ins.curPageId)
        }
    }
    showRecommendUI() {
        let show = GameManager.ins.canShowRecommendUI();
        if (!show) return;
        // 每天弹一次
        let levelInfo = LevelManager.ins.getRecommendLevel();
        if (levelInfo) {
            UIManager.ins.showPop("recommendUI", BUNDLE_TYPE_ENUM.HOME, levelInfo);
            GameManager.ins.saveRecommedTime();
        }
    }
    /** 初始化按钮i回调 */
    initBtnClick() {
        // this.lastBtn.node.on("click" , () => {
        //     this.moveToLevelItem(-1);
        // } );
        // this.nextBtn.node.on("click", () => {
        //     this.moveToLevelItem(1);
        // } );
    }
    /**列表按钮初始话 */
    initLvBtn() {
        // if (AdManager.gameId != 5 && AdManager.gameId != 0) {
        this.moreLv.node.active = false;
        // this.newLv.node.active = true;
        this.newLv.node.active = false;
        // this.btnSuggest.active = true;
        // // } else {
        // //     this.moreLv.node.active = false;
        // //     this.newLv.node.active = false;
        // //     this.btnSuggest.active = false;
        // // }
    }

    /** 初始化scrollview */
    initScrollView(lvInfo?: LvInfo[]) {
        /** 列表末尾加一个敬请期待 */
        let infos = LevelManager.ins.getLvInfoArr();
        if (lvInfo) {
            infos = lvInfo;
        }
        let totalPage = Math.ceil((infos.length + 1) / LEVEL_NUM_IN_PAGE);
        this.totalPageLbl.string = totalPage.toString();

        let lvInfoList = new Array(totalPage).fill([]).map(() => new Array())
        let i = 0, j = 0;
        for (let k = 0; k <= infos.length; k++) {
            let data = infos[k];
            lvInfoList[i][j++] = data ? data : null;
            if (j === LEVEL_NUM_IN_PAGE) {
                i++;
                j = 0;
            }
        }
        // cc.log(lvInfoList)
        this.listView.initList(LevelManager.ins.curPageId, lvInfoList);
        this.updatePageLab(LevelManager.ins.curPageId);
    }
    /** 界面动画 */
    startAnim() {
        UIManager.ins.enabledClick(false);
        // this.bg.opacity = 0;
        let root = this.node.getChildByName("root");
        this.scheduleOnce(() => {
            root.x += root.width;
            root.opacity = 255;
            // cc.tween(this.bg).to(0.2, { opacity: 255 }).start();
            cc.tween(root).by(0.3, { position: cc.v3(-root.width, 0, 0) }).call(() => {
                UIManager.ins.enabledClick(true);
            }).start();

            // ActionTools._ins.moveByOutInit(this.closeBtn.node, 0.3, -200, 0);
        }, 0);
    }


    initUnlockBtn() {
        // this.unlockAllBtn.active = !LevelManager.ins.isUnlockAll();
    }
    initGiftBtn() {
        // this.giftBtn.active = true;
        AdManager.isShowGiftBtn((active: boolean) => {
            this.entryBtn.node.active = active;
        });
    }
    initAddBtn() {
        this.addBtn.active = false;
        this.changwanBtn.node.active = false;
        if (AdManager.releaseType === RELEASE_TYPE_ENUM.ks) {
            this.addBtn.active = false;
            AdManager.isShowChangWanBtn((active: boolean) => {
                console.log("是否开启常玩按钮2", active);
                this.changwanBtn.node.active = active;
            })
            return;
        }
        // AdManager.isShowAddShortcutBtn((active: boolean) => {
        //     this.addBtn.active = active;
        // });
    }
    hideGiftBtn() {
        // this.giftBtn.active = false;
        this.entryBtn.node.active = false;
    }
    hideAddBtn() {
        this.addBtn.active = false;
    }

    /** 设置页数 */
    updatePageLab(pageNum: number) {
        LevelManager.ins.curPageId = pageNum;
        this.pageIdxLbl.string = pageNum.toString();
    }

    /** 解锁关卡 */
    unlockLevel() {
        this.listView.getCurrentPage().updateItemLockState();
    }
    /** 解锁所有关卡 */
    unlockAllLevel() {
        // this.unlockAllBtn.active = false;
        // this.listView.updateLockState();
    }
    clickBtnClose() {
        AudioManager1.playClick();
        UIManager.ins.enabledClick(false);
        // cc.tween(this.bg).to(0.2, { opacity: 0 }).start();
        let root = this.node.getChildByName("root");
        cc.tween(root).by(0.3, { position: cc.v3(root.width, 0, 0) })
            .call(() => {
                AudioManager1.stopBG();
                UIManager.ins.enabledClick(true);
                UIManager.ins.close();
                // UIManager.ins.showUI("startUI", BUNDLE_TYPE_ENUM.HOME);
                // Message.instance.send(EventID.EXIT_NAODONG);

                // 刷新矿村页面
                const talkData = StorageUtil.instance.getTalkData();
                if (talkData.id < 10412) {
                    talkData.id = 10412;
                    TalkModule.updateAllCheck();
                }
            }).start();

        // cc.tween(this.closeBtn.node).by(0.2, { position: cc.v3(-200, 0) }, { easing: "backIn" }).start();
    }
    /** 点击解锁全部 */
    clickBtnUnlockAll() {
        AudioManager1.playClick();
        UIManager.ins.showPop("LockLvUI", BUNDLE_TYPE_ENUM.HOME, true);
    }
    /** 点击礼包 */
    clickBtnGift() {
        AudioManager1.playClick();
        // if (AdManager.releaseType == RELEASE_TYPE_ENUM.wechat || AdManager.releaseType === RELEASE_TYPE_ENUM.ks) {
        //     UIManager.ins.showPop('signUI', BUNDLE_TYPE_ENUM.HOME);
        //     return;
        // }
        // if (AdManager.fuFangFinished()) {
        //     UIManager.ins.showPop('signUI', BUNDLE_TYPE_ENUM.HOME);
        // } else {
        //     UIManager.ins.showPop('douyinPropUI', BUNDLE_TYPE_ENUM.HOME);
        // }
        UIManager.ins.showPop('signUI', BUNDLE_TYPE_ENUM.HOME);
    }

    clickBtnEntry() {
        AudioManager1.playClick();
        UIManager.ins.showPop('douyinPropUI', BUNDLE_TYPE_ENUM.HOME);
    }

    /** 点击添加桌面 */
    clickBtnAddShortCut() {
        AudioManager1.playClick();
        // UIManager.ins.showPop('addShortcutUI', BUNDLE_TYPE_ENUM.HOME);
        AdManager.addTable(() => EventManager.ins.emit(EVENT_NAME_ENUM.HIDE_ADD_SHORTCUT_BTN));
    }

    clickBtnChangWan() {
        AdManager.addCommonUse(() => {
            this.hideChangwanBtn();
        })
    }

    /**点击最新关卡 */
    clickNewLvBtn() {
        if (this.isSelectLvType) {
            return;
        }
        this.isSelectLvType = true;
        this.selectNewList(1);
        this.scheduleOnce(() => {
            this.isSelectLvType = false;
        }, 0.5)
    }

    /**点击更多关卡 */
    clickMoreLvBtn() {
        if (this.isSelectLvType) {
            return;
        }
        this.isSelectLvType = true;
        this.newLv.node.active = true;
        this.moreLv.node.active = false;
        let infos = LevelManager.ins.getLvInfoArr();
        LevelManager.ins.isSelectNewList = false;
        this.refreshListView(infos, 1);
        this.scheduleOnce(() => {
            this.isSelectLvType = false;
        }, 0.5)
    }

    /**选择最新关卡列表 */
    selectNewList(pageId: number) {
        this.newLv.node.active = false;
        this.moreLv.node.active = true;
        let newLvInfo = LevelManager.ins.getNewListInfoArr();
        LevelManager.ins.isSelectNewList = true;
        this.refreshListView(newLvInfo, pageId);

        this.scheduleOnce(() => {
            let scrollView = this.listView.node.getComponent(cc.ScrollView)
            let offset = scrollView.getScrollOffset();
            offset.x = -offset.x + 1;
            this.listView.isScroling = true;
            scrollView.scrollToOffset(offset, 0.05);
        }, 0.01)
    }

    /**反馈意见建议 */
    clickBtnSuggest() {
        UIManager.ins.showPop('suggestUI', BUNDLE_TYPE_ENUM.HOME);
    }

    hideChangwanBtn() {
        this.changwanBtn.node.active = false;
    }

    /**搜索关卡 */
    searchLevel() {
        let lvName = this.searchBox.string;
        if (lvName != "" && lvName != this.tempLvName) {
            this.tempLvName = lvName;
            let infos = LevelManager.ins.getLvInfoArr();
            let getInfo = [];
            for (let item of infos) {
                if (item.name.indexOf(lvName) != -1) {
                    getInfo.push(item);
                }
            }
            this.refreshListView(getInfo, 1);
        }
    }

    /**刷新关卡列表 */
    refreshListView(lvInfo: LvInfo[], pageId?: number) {
        if (lvInfo.length > 0) {
            let totalPage = Math.ceil((lvInfo.length + 1) / LEVEL_NUM_IN_PAGE);
            this.totalPageLbl.string = totalPage.toString();
            let lvInfoList = new Array(totalPage).fill([]).map(() => new Array())
            let i = 0, j = 0;
            for (let k = 0; k <= lvInfo.length; k++) {
                let data = lvInfo[k];
                lvInfoList[i][j++] = data ? data : null;
                if (j === LEVEL_NUM_IN_PAGE) {
                    i++;
                    j = 0;
                }
            }
            if (!pageId) {
                pageId = LevelManager.ins.curPageId;
            }
            this.listView.initList(pageId, lvInfoList);
            this.updatePageLab(pageId);
        }
    }

    /** 刷新上一关下一关按钮显示 */
    updateBtnShow() {
        // this.lastBtn.node.active = true;
        // this.nextBtn.node.active = true;
        // if(LevelManager.ins.curPageId <= 1){
        //     this.lastBtn.node.active = false;
        // }else if(LevelManager.ins.curPageId >= parseInt(this.totalPageLbl.string)) {
        //     this.nextBtn.node.active = false;
        // }
    };
    /** 移动至某页 */
    gotoPage(addNum: number) {
        this.updatePageLab(LevelManager.ins.curPageId);
        LevelManager.ins.curPageId += addNum;
    }

    clickBtnNext() {
        if (this.isTouchedPage) return;
        this.isTouchedPage = true;
        let scrollView = this.listView.node.getComponent(cc.ScrollView)
        let offset = scrollView.getScrollOffset();
        offset.x = -offset.x + 750;
        this.listView.isScroling = true;
        scrollView.scrollToOffset(offset, 0.4);
        this.scheduleOnce(() => {
            this.isTouchedPage = false;
        }, 0.4)
    }

    clickBtnLast() {
        if (this.isTouchedPage) return;
        this.isTouchedPage = true;
        let scrollView = this.listView.node.getComponent(cc.ScrollView)
        let offset = scrollView.getScrollOffset();
        offset.x = -offset.x - 750;
        this.listView.isScroling = true;
        scrollView.scrollToOffset(offset, 0.4);
        this.scheduleOnce(() => {
            this.isTouchedPage = false;
        }, 0.4)
    }

    updateAddLiveState() {
        this.node.getChildByName("root").getChildByName("liveLvList").active = this.node.getChildByName("reset").active =
            this.node.getChildByName("starLive").active = false;
        let isLiveLevelActive = Tools.getStorage('setLiveLvActive');
        if (isLiveLevelActive && isLiveLevelActive != "false") {
            this.node.getChildByName("root").getChildByName("liveLvList").active = this.node.getChildByName("reset").active =
                this.node.getChildByName("starLive").active = true;
            this.updateLiveLvList();
        }
    }

    /**开始直播 */
    startLive() {
        let liveLvInfos = LevelManager.ins.liveLvInfos;
        if (liveLvInfos && liveLvInfos.length > 0) {
            LevelManager.ins.isLiveing = true;
            LevelManager.ins.loadLevelPre(liveLvInfos[0]);
        }
    }

    /**清除直播关卡 */
    resetLiveLvList() {
        this.liveLvCon.removeAllChildren();
        LevelManager.ins.removeLiveLvInfos();
    }

    /**更新直播关卡列表 */
    updateLiveLvList() {
        let liveLvInfos = LevelManager.ins.liveLvInfos;
        this.liveLvCon.removeAllChildren();
        if (liveLvInfos && liveLvInfos.length > 0) {
            let idx = 0;
            for (let item of liveLvInfos) {
                idx++;
                let lbLive = cc.instantiate(this.liveLvName);
                lbLive.getComponent(cc.Label).string = idx + "." + item.name;
                this.liveLvCon.addChild(lbLive);
                lbLive.x = 0;
            }
        }
    }
}
AppService.instance.registViewData(VIEW_DATA);